package middleware

import (
	"errors"
	"fmt"
	"k8s-admin/utils"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func ChecKToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("Authorization")
		if tokenString == "" {
			//c, errorx.TokenError, errors.New("token解析失败").Error()
			utils.ReturnContext(c).Failed("失败", errors.New("token解析失败").Error())
			c.Abort()
			return
		} else if strings.Split(tokenString, " ")[0] != "Bearer" {
			utils.ReturnContext(c).Failed("失败", "token格式错误")
			c.Abort()
			return

		}
		//	校验token合法性
		token, err := utils.ParseToken(strings.Split(tokenString, " ")[1])
		if err != nil {
			utils.ReturnContext(c).Failed("失败", errors.New("token解析失败").Error())
			c.Abort()
			return
		}
		// 判断过期时间
		if time.Now().Unix() > token.ExpiresAt.Unix() {
			utils.ReturnContext(c).Failed("失败", errors.New("token授权过期"))
			c.Abort()
			return
		} else {
			fmt.Printf("username:%s", token.TokenInfo.Username)
			c.Set("userId", token.ID)
			c.Set("username", token.TokenInfo.Username)
			c.Next()
		}
	}
}
